package com.rx.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rx.entity.Admin;
import com.rx.entity.Logs;
import com.rx.service.AdminServiceI;
import com.rx.service.AdminServiceImpl;
import com.rx.service.LogsServiceI;
import com.rx.service.LogsServiceImpl;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/AdminServlet")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		AdminServiceI asi = new AdminServiceImpl();
		String login = request.getParameter("login");
		if ("out".equals(login)) {
			//销毁session
			HttpSession session = request.getSession();
			System.out.println("退出登录");
			session.invalidate();
			response.sendRedirect("/admin/login.html");
		} else {
			// 读数据使用get
			try {
				List<Admin> list = asi.getAll();
				// 通过 request 将获取到的数据传给页面
				request.setAttribute("list", list);
				for (Admin admin : list) {
					System.out.println(admin.getCreateDate());
				}
				// 请求转发
				request.getRequestDispatcher("admin/admin.jsp").forward(request, response);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * view界面跳转到该方 此方法会调用 业务层的方法进行用户名密码认证
	 * 
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username + ":" + password);
		// 创建业务层对象
		AdminServiceI asi = new AdminServiceImpl();
		try {
			// 判断用户密码是否正确
			if (asi.login(username, password)) {
				// 获取一个会话，将用户值放入会话中
				HttpSession session = request.getSession();
				session.setAttribute("username", username);
				/***************** 添加登录日志 *******************/
				LogsServiceI lsi = new LogsServiceImpl();
				Logs logs = new Logs();
				logs.setOperateType(0);
				logs.setContent(username + "登录成功。");
				lsi.add(logs);

				response.sendRedirect("/admin/index.jsp");
			} else {
				response.sendRedirect("/error.jsp");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
